package com.school.teaching.util;

import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

import java.io.IOException;
import java.util.Map;

import okio.BufferedSink;

/**
 * Created by hesheng on 2017/6/1.
 */

public final class OkHttpUtils {

    private static final OkHttpClient client = new OkHttpClient();
    private static final MediaType MEDIA_TYPE_JSON = MediaType
            .parse("application/json; charset=utf-8");

    /**
     * POST提交Json数据
     *
     * @param url
     * @param json
     * @return
     * @throws IOException
     */
    public static String post(String url, final String json) throws IOException {
        // RequestBody body = RequestBody.create(MEDIA_TYPE_JSON, json);
        RequestBody body = new RequestBody() {
            @Override
            public MediaType contentType() {
                return MEDIA_TYPE_JSON;
            }

            @Override
            public void writeTo(BufferedSink sink) throws IOException {
                sink.writeUtf8(json);
            }

            @Override
            public long contentLength() throws IOException {
                return json.length();
            }
        };
        Request request = new Request.Builder().url(url).post(body).build();
        Response response = null;
        try {
            response = client.newCall(request).execute();
        } catch (Exception e) {
            throw new IOException("服务器端连接断开，url：" + url, e);
        }
        if (response.isSuccessful()) {
            return response.body().string();
        } else {
            throw new IOException("服务器端错误:" + response);
        }
    }

    /**
     * POST提交键值对
     *
     * @param url
     * @param params
     * @return
     * @throws IOException
     */
    public static String post(String url, Map<String, String> params)
            throws IOException {
        FormEncodingBuilder builder = new FormEncodingBuilder();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            builder.add(key, value);
        }
        RequestBody body = builder.build();

        Request request = new Request.Builder().url(url).post(body).build();
        Response response = null;
        try {
            response = client.newCall(request).execute();
        } catch (Exception e) {
            throw new IOException("服务器端连接断开", e);
        }
        if (response.isSuccessful()) {
            return response.body().string();
        } else {
            throw new IOException("服务器端错误:" + response);
        }
    }
}
